<template>
  <div class="app-container calendar-list-container">
    <!-- filter 条件查询 -->
    <div class="filter-container">
      <el-input 
      clearable 
      @keyup.enter.native="handleFilter" 
      v-model="listQuery.batteryId" style="width: 200px;margin-right:15px;"  :placeholder="$t('device.Powerbank_ID')" >
      </el-input>
      <el-input 
      clearable 
      @keyup.enter.native="handleFilter" 
      v-model="listQuery.batteryNumber" style="width: 200px;margin-right:15px;"  :placeholder="$t('device.Powerbank_serial_number')" >
      </el-input>
      <el-select  clearable v-model="listQuery.batteryStatus" :placeholder="$t('device.category')">
        <el-option v-for="item in badType" :label="item.label" :value="item.value" :key="item.value"></el-option>
      </el-select>
      <el-button  type="primary" v-waves icon="el-icon-search" @click="handleFilter">{{$t('device.Find')}}</el-button>
      <el-button type="primary"  v-waves icon="el-icon-circle-plus-outline" @click="dialog.add = true" >{{$t('device.Add')}}</el-button>
      <el-button  type='primary' v-waves   icon="el-icon-upload" @click='uploadBtn'  :loading="uploadLoading">{{$t('device.Import')}}</el-button>
      <el-button  type='primary' v-waves   @click="handleDownload"  icon="el-icon-download"  :loading="downloadLoading">{{$t('device.Export')}}</el-button>
    </div>
    <!-- table 表格 -->
    <el-table  :data="list" v-loading="loading.list" element-loading-text="给我一点时间" border fit highlight-current-row
      style="width: 100%">
      <el-table-column  :label="$t('device.Powerbank_ID')" prop='batteryId' />
      <el-table-column  :label="$t('device.Powerbank_serial_number')" prop='batteryNumber' />
      <el-table-column  :label="$t('device.Cabinet_name')" prop='equipmentNumber' />
      <el-table-column  :label="$t('device.Slot_number')" prop='slot' />
      <el-table-column  :label="$t('device.Number_of_powerbank_using')" prop='batteryUseNum' />
      <el-table-column  :label="$t('device.Powerbank_status')">
         <template slot-scope="scope">
           <div :style="{'color': scope.row.batteryStatus > 2 ? 'red' : 'blue'}">
             {{scope.row.batteryStatus | batteryStatus }}
           </div>
        </template>
      </el-table-column>
      <el-table-column  :label="$t('device.Created_time')">
         <template slot-scope="scope">
           {{scope.row.ctime | parseTime}}
        </template>
      </el-table-column>
       <el-table-column  :label="$t('device.First_borrow_time')" prop='leaseStartTime' />
      <el-table-column  :label="$t('device.Scrap_time')" prop='leaseEndTime'>
      </el-table-column>
      <el-table-column  :label="$t('device.Using_time')" prop='hourage' />
      <el-table-column  :label="$t('device.Check_battery')">
        <template slot-scope="scope">
          <div class="fx">
            <el-button type="primary" v-if="scope.row.batteryStatus == 1" @click="getEnergy(scope.row)">{{$t('device.View')}}</el-button>          
          </div>
        </template>
      </el-table-column>
      <el-table-column  :label="$t('device.Operate')"  width="300">
        <template slot-scope="scope">
          <div class="fx">
            <el-button type='danger' v-if="scope.row.batteryStatus  <= 2" @click="updateBattery(scope.row, 4)">{{$t('device.Report_loss')}}</el-button>
            <el-button type='danger' v-if="scope.row.batteryStatus <= 2" @click="updateBattery(scope.row, 3)">{{$t('device.Report_Damaged')}}</el-button>
            <el-button type="danger" @click="delBattery(scope.row)">{{$t('device.Delete')}}</el-button>          
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination 
      background 
      @size-change="handleSizeChange" 
      @current-change="handleCurrentChange" 
      :current-page="listQuery.pageNo" 
      :page-sizes="[10, 20, 30, 40]" 
      :page-size="listQuery.pageSize" 
      layout="total, sizes, prev, pager, next, jumper" 
      :total="total">
      </el-pagination>
    </div>
    <!-- 新增弹框 -->
    <el-dialog :title="$t('device.Add_Powerbank')" :visible.sync="dialog.add">
      <el-form :model="addQuery" :rules='addRules' ref="addForm"  label-position="right" label-width="120px"> 
        <el-form-item :label="$t('device.Powerbank_serial_number')" prop="batteryNumber">
         <el-input  clearable v-model="addQuery.batteryNumber" :placeholder="$t('device.Powerbank_serial_number')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('device.Scrap_time')" prop="endTime">
          <el-date-picker
            v-model="addQuery.endTime"
            type="datetime"
            value-format="timestamp"
            :placeholder="$t('recommend.Select_date')">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.add = false">{{$t('device.Cancel')}}</el-button>
        <el-button type="primary" :loading="loading.add" @click="add">{{$t('device.Submit')}}</el-button>
      </div>
    </el-dialog>
     <!-- 新增弹框 -->
    <el-dialog :title="$t('device.Check_battery')" :visible.sync="dialog.view">
      <div v-loading='loading.detail'>
        {{$t('device.Electricity')}}：{{battery}}
      </div>
    </el-dialog>
    <!-- 导入excel -->
    <input type="file" @change="uploadExcel" ref='uploadExcel' style="display:none">
    <!-- 回到顶部 -->
    <BackToTop></BackToTop>
  </div>
</template>

<script>
import { 
  getBatteryList as getList, 
  addEquipment, 
  delBattery,
  updateBattery,
  addBattery,
  exportExcel,
  getEnergy
} from '@/api/equipment'
import { validatePhone } from '@/utils/validate'
import { parseTime } from '@/utils'
import BackToTop from '@/components/BackToTop'
export default {
  filters: {
    batteryStatus (val) {
      const lvs = ['空闲', '使用中', '故障', '报失']
      return lvs[val - 1]
    }
  },
  components: {
    BackToTop
  },
  name: 'equipment_list',
  data() {
    return {
      total: 0,
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        batteryId: '',
        batteryNumber:'',
        batteryStatus: ''
      },
      list: null,
      loading: {
        list: false,
        add: false,
        bind: false,
        detail: false
      },
      dialog:{
        add:false,
        bind: false,
        detail: false,
        basic: false,
        view: false
      },
      addQuery:{
        batteryNumber: '',
        endTime: '',
      },
      addRules: {
          batteryNumber: [
            { required: true, message: this.$t('device.Powerbank_serial_number'), trigger: 'blur' }
          ],
          endTime: [
            { required: true, message: this.$t('recommend.Select_date'), trigger: 'blur' }
          ],
      },
      downloadLoading: false,
      uploadLoading: false,
      badType: [
        {
          label: '正常',
          value: 1
        },
        {
          label: '使用中',
          value: 2
        },
        {
          label: '故障',
          value: 3
        },
         {
          label: '报失',
          value: 4
        },

      ],
      battery: 0
    }
  },
  methods: {
    async getEnergy ({batteryId}) {
      this.dialog.view = true
      this.loading.detail = true
      try {
          const res = await getEnergy({batteryId})
          if (res.code === 1) {
            this.battery = res.data
          }
      } catch (error) {
        this.loading.detail = false
      }
      this.loading.detail = false
    },
    // 挂失或报损
    async updateBattery ({batteryId}, batteryStatus) {
      const msg = batteryStatus === 3 ? '报损' : '挂失'
      const res = await updateBattery({
        batteryId,
        batteryStatus
      })
      if (res.code === 1) {
        this.$message.success(this.$t('common.Successful_operation'))
        this.getList()
      }
    },
    // 删除充电宝
    async delBattery ({batteryId}) {
      const res = await delBattery({id: batteryId})
      if (res.code === 1) {
        this.$message.success(this.$t('common.Successful_operation'))
        this.getList()
      }
    },
    // 导入按钮
    uploadBtn () {
      this.$refs.uploadExcel.click()
    },
    // 上传excel
    async uploadExcel (e) {
      this.uploadLoading = true
      try {
        const excel = e.target.files[0]
        const fd = new FormData()
        fd.append('excel', excel)
        const res = await exportExcel(fd)
        if (res.code === 1) {
          this.$message.success(this.$t('common.Successful_operation'))
          this.getList()
        }
      } catch (error) {
        this.$refs.uploadExcel.value = ''
        this.uploadLoading = false
      }
      this.uploadLoading = false
       this.$refs.uploadExcel.value = ''
    },
    //导出
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['充电宝id', '充电宝序列号', '设备序列号','槽号', '充电宝使用次数', '使用情况','充电宝状态','创建时间','首次租借时间','报废时间', '使用时长']
        const filterVal = ['batteryId', 'batteryNumber', 'equipmentNumber','slot', 'batteryUseNum', 'isFlagL','batteryStatusL','ctime', 'leaseStartTime', 'leaseEndTime', 'hourage']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '充电宝列表'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
      if (j === 'ctime') {
        return parseTime(v[j])
      } else {
        return v[j]
      }
      }))
    },
    async getList() {
      this.loading.list = true
      try {
        // parseTime
        const { data } = await getList(this.listQuery)
        const lvs = ['正常', '使用中', '故障', '报失']
        this.list = data.records.map((item, index) => ({
          index: index + 1, 
          ...item,
          leaseStartTime: parseTime(item.leaseStartTime),
          leaseEndTime: parseTime(item.leaseEndTime),
          isFlagL: item.isFlag == 1 ? '使用中' : '空闲',
          batteryStatusL: lvs[item.batteryStatus-1]
        }))
        this.total = data.total
      } catch (error) {
        
      }
      this.loading.list = false     
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val
      this.getList()
    },
    // 新增设备
    async add() {
      this.$refs['addForm'].validate(async (valid) => {
          if (valid) {
            this.loading.add = true
            try{
              const res = await addBattery(this.addQuery)
              if (res.code === 1) {
                this.$message({
                  type:'success',
                  message: this.$t('common.Successful_operation')
                })
                this.getList()
                this.$refs['addForm'].resetFields();
                this.dialog.add = false
              }
             
            } catch(error) {
              this.loading.add = false
            }
            this.loading.add = false
          } else {
            console.log('error submit!!');
            return false;
          }
        });
     
    },
  }, 
  created() {
    this.getList()
  },
  computed: {
    basicTitle () {
      return this.basicType == 1 ? '分成设置' : '收费设置'
    }
  }
}
</script>
<style lang="scss" scoped>
._c {
  border: 1px solid #000;
  border-radius: 8px;
  padding: 10px;
  display: flex;
  flex-direction: column;
}
.e_item {
  border: 1px solid #000;
  border-radius: 8px;
  padding: 10px;
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
</style>

